#include"mystdio.h"
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>
#include<unistd.h>

mFILE* mfopen(char* filename,char* mode)
{
    int fd = -1;
    if(strcmp(mode,"r") == 0)
    {
        fd = open(filename,O_RDONLY);
    }
    else if(strcmp(mode, "w") == 0) 
    {
        fd = open(filename, O_WRONLY | O_CREAT| O_TRUNC,0666);
    }
    else if(strcmp(mode,"a") == 0)
    {
        fd = open(filename, O_WRONLY | O_CREAT| O_APPEND, 0666);
    }
    if(fd < 0)
        return NULL;
    mFILE* fp = (mFILE*)malloc(sizeof(mFILE));
    if(fp == NULL)
    {
        close(fd);
        return NULL;
    }
    fp->fileno = fd;
    fp->flag = FFLUSH_LINE;
    fp->size = 0;
    fp->capa = SIZE;
    return fp;
}
int mfwrite(const char* ptr, int num, mFILE* stream )
{
    memcpy(stream->filebuffer+stream->size,ptr,num);
    stream->size += num;
    if(stream->flag == FFLUSH_LINE && stream->size > 0 && stream->filebuffer[stream->size - 1] == '\n')
    {
        mfflush(stream);
    }
    return num;
}

void mfflush(mFILE* stream)
{
    if(stream->size > 0)
    {
       write(stream->fileno,stream->filebuffer,stream->size);

       stream->size = 0;
    }
}

void mfclose(mFILE* stream)
{
    //先检查是否要刷新
    if(stream->size > 0)
    {
        mfflush(stream);
    }
    close(stream->fileno);
}
